//
//  SplashViewController.m
//  Kaagad Peso
//
//  Created by ZhengChengFeng on 2024/10/16.
//

#import "SplashViewController.h"

@interface SplashViewController ()

@property (nonatomic) NSTimer *timer;

@property (nonatomic) BOOL isNetwork;

@property (nonatomic) UILabel *titleLab;
@property (nonatomic) UIButton *btn;

@end

@implementation SplashViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}


- (void)isHaveNetWork{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == 1 || status == 2){
            self.isNetwork = YES;
        }
        else{
            self.isNetwork = NO;
        }
        
        if (self.isNetwork == NO) {
            [self initUI];
        }
        else{
        
            if (self.titleLab) {
                [self.titleLab removeFromSuperview];
            }
            if (self.btn) {
                [self.btn removeFromSuperview];
            }
        
        }
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
        
    [[NSUserDefaults standardUserDefaults] setObject:@"en" forKey:kAppLanguage];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    self.view.backgroundColor = [UIColor clearColor];
    
    UIImage *img = [UIImage imageNamed:@"LaunchImg"];
    UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    imgV.contentMode = UIViewContentModeScaleToFill;
    [self.view addSubview:imgV];
    imgV.image = img;
        
    [self isHaveNetWork];
    
    self.timer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(netWorkRequest) userInfo:nil repeats:YES];
        
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}

- (void)netWorkRequest{
    if (self.isNetwork == NO) {
        [self isHaveNetWork];
    }
    else{
        
        if (self.timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
        
        [BoxLoadingHelper showBoxLoadingWithMessage:@""];
        NSMutableDictionary *muDic = @{
            @"islets":[self isOpenProxy] ? @"1":@"0",
            @"craving":[self isOpenVPN] ? @"1":@"0",
            @"instances":@"id-id",
        }.mutableCopy;
        [HttpNetHelper postNetworkHelperForPath:kCheckLaungageUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
            [BoxLoadingHelper hideBoxLoading];
            if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
                [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
                return;
            }
            
            NSDictionary *dic = responseDic[@"clip"];
            NSString *seawardStr = esString(dic[@"seaward"]);
           
            [[NSUserDefaults standardUserDefaults] setObject:seawardStr forKey:kCurrentLanguageCode];
            
            
            if ([seawardStr integerValue] == 500) {
                [[NSUserDefaults standardUserDefaults] setObject:@"id" forKey:kAppLanguage];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
            }else{
                [[NSUserDefaults standardUserDefaults] setObject:@"en" forKey:kAppLanguage];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
                        
            [self getAllLanguage];
            [self currentUseLanguage];
            
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[DKCore sharedDKCore] loadMainTabbarController];
            
        } onCompleteFailur:^(NSError * _Nonnull error) {
            [BoxLoadingHelper hideBoxLoading];
            [BoxLoadingHelper showBoxWithMessage:error.localizedDescription];
        } withIsForm:YES];
        

    }
    
}

- (void)initUI{
    
    if (self.titleLab) {
        [self.titleLab removeFromSuperview];
    }
    if (self.btn) {
        [self.btn removeFromSuperview];
    }

    NSString *titleStr = ASLocalizedString(@"NetError");
    NSString *btnStr = ASLocalizedString(@"Try Again");
    
    UILabel *titleLab = [UILabel createLabel:[UIFont fontWithName:kFuturaMedium size:13] color:[UIColor colorWithHexString:@"#6C6C6C"]];
    titleLab.numberOfLines = 2;
    titleLab.textAlignment = 1;
    [self.view addSubview:titleLab];
    titleLab.frame = CGRectMake(40, kScreenHeight/2 - 50 + 15, kScreenWidth - 80, 50);
    titleLab.text = titleStr;
    self.titleLab = titleLab;
    
    self.btn = [[UIButton alloc] init];
    self.btn.titleLabel.font = [UIFont fontWithName:kFuturaMedium size:13];
    [self.btn setTitle:btnStr forState:UIControlStateNormal];
    [self.btn setTitle:btnStr forState:UIControlStateSelected];
    [self.btn setTitle:btnStr forState:UIControlStateHighlighted];
    [self.btn setTitleColor:kButtonDefaultColor forState:UIControlStateNormal];
    [self.btn setTitleColor:kButtonDefaultColor forState:UIControlStateSelected];
    [self.btn setTitleColor:kButtonDefaultColor forState:UIControlStateHighlighted];
    [self.view addSubview:self.btn];
    
    self.btn.frame = CGRectMake((kScreenWidth - 110)/2, self.titleLab.bottom + 5, 110, 40);
    
    self.btn.layer.cornerRadius = 20;
    self.btn.layer.masksToBounds = YES;
    self.btn.layer.borderColor = kButtonDefaultColor.CGColor;
    self.btn.layer.borderWidth = 1;
    
    [self.btn addTarget:self action:@selector(clickBtn) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)clickBtn{
    
    [[DKCore sharedDKCore] showNetErrorAlertView];
    
}

- (void)getAllLanguage{
    NSArray *languages = [[NSBundle mainBundle] localizations];
    for (NSString *language in languages) {
        NSLog(@"Supported language: %@", language);
    }

}

- (void)currentUseLanguage{
    NSArray *systemLanguages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [systemLanguages objectAtIndex:0];
    NSLog(@"Current system language: %@", currentLanguage);

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (BOOL)isOpenProxy{
    NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
    NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"https://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
    NSDictionary *settings = proxies[0];
    if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]) {
        return NO;
    }
    return YES;
    
}

- (BOOL)isOpenVPN{
    BOOL flag = NO;
    NSDictionary *dict = CFBridgingRelease(CFNetworkCopySystemProxySettings());
    NSArray *keys = [dict[@"__SCOPED__"] allKeys];
    for (NSString *key in keys) {
        if ([key rangeOfString:@"tap"].location != NSNotFound ||
            [key rangeOfString:@"tun"].location != NSNotFound ||
            [key rangeOfString:@"ipsec"].location != NSNotFound ||
            [key rangeOfString:@"ppp"].location != NSNotFound){
            flag = YES;
            break;
            
        }
    }
    return flag;
}
 
@end
